package com.tinyblog.ajax2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class BlogService {
	private Document blogdom;
	private Document listdom;
	/**
	 * 构造函数，初始化DOM连接
	 *
	 */
	public BlogService() {
		try {
			SAXBuilder builder = new SAXBuilder();
			this.blogdom = builder.build(BlogService.class.getResource("blog.xml"));
			this.listdom = builder.build(BlogService.class.getResource("list.xml"));
		}catch(Exception ex) {
			this.handleError(ex);
		}
	}
	/**
	 * 获取日志列表，以对象数组的形式返回，用于显示，不包含评论和引用
	 * @return
	 */
	public Blog[] getAllBlog() {
		Collection bloges = new ArrayList();
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				Blog blog = new Blog(element);
				bloges.add(blog);
			}while(iterator.hasNext());
			return (Blog[])bloges.toArray(new Blog[0]);
		}
		else 
			return new Blog[0];
	}
	/**
	 * 获取日志列表，以Map的形式返回，用户持久化，包含评论和引用
	 * @return
	 */
	public Map getAllBlogMap() {
		Map bloges = new HashMap();
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				Blog blog = new Blog();
				blog.initialBlog(element);
				bloges.put(blog.getId(),blog);
			}while(iterator.hasNext());
		}
		return bloges;
	}
	/**
	 * 获取指定的日志，包含其评论和引用
	 * @param id
	 * @return
	 */
	public Blog getBlog(String id) {
		Blog blog = null;
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("id").equalsIgnoreCase(id)){
					blog = new Blog();
					blog.initialBlog(element);
				}
			}while(iterator.hasNext());
		}
		return blog;
	}
	/**
	 * 增加日志
	 * @param blog
	 * @throws Exception
	 */
	public void addBlog(Blog blog) throws Exception {
		Map bloges = this.getAllBlogMap();
		blog.setId(String.valueOf(bloges.size()));
		bloges.put(blog.getId(),blog);
		this.outputXMLDocument((Blog[])bloges.values().toArray(new Blog[0]));
	}
	/**
	 * 获取指定日志的评论列表，以对象数组的形式返回
	 * @param blogid
	 * @return
	 */
	public BlogComment[] getComment(String blogid) {
		Collection commentes = new ArrayList();
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("id").equalsIgnoreCase(blogid)) {
					if(element.getChild("comments").getChildren().size()!=0) {
						Iterator cIterator = element.getChild("comments").getChildren().iterator();
						do {
							Element cElement = (Element)cIterator.next();
							BlogComment comment = new BlogComment(cElement);
							commentes.add(comment);
						}while(cIterator.hasNext());
					}
				}
			}while(iterator.hasNext());
		}
		return (BlogComment[])commentes.toArray(new BlogComment[0]);
	}
	/**
	 * 获取指定日志的评论列表，以Map对象的形式返回
	 * @param blogid
	 * @return
	 * @throws Exception
	 */
	public Map getCommentMap(String blogid) throws Exception {
		Map comments = new HashMap();
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("id").equalsIgnoreCase(blogid)) {
					if(element.getChild("comments").getChildren().size()!=0) {
						Iterator cIterator = element.getChild("comments").getChildren().iterator();
						do {
							Element cElement = (Element)cIterator.next();
							BlogComment comment = new BlogComment(cElement);
							comments.put(comment.getCommentdate(),comment);
						}while(cIterator.hasNext());
					}
				}
			}while(iterator.hasNext());
		}
		return comments;
	}
	/**
	 * 添加指定日志的评论
	 * @param comment
	 * @param blogid
	 * @throws Exception
	 */
	public void addComment(BlogComment comment, String blogid) throws Exception {
		Map bloges= this.getAllBlogMap();
		if((bloges!=null)&&(bloges.size()!=0)) {
			Blog[] bArray = (Blog[])bloges.values().toArray(new Blog[0]);
			for(int i=0;i<bArray.length;i++) {
				if(blogid.equalsIgnoreCase(bArray[i].getId())) {
					bArray[i].addComment(comment);
					break;
				}
			}
			this.outputXMLDocument(bArray);
		}
		else throw new Exception("未找到指定日志。");
	}
	/**
	 * 获取指定日志的引用列表，以对象数组的形式返回
	 * @param blogid
	 * @return
	 */
	public BlogReference[] getReference(String blogid) {
		Collection references = new ArrayList();
		if(this.blogdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.blogdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("id").equalsIgnoreCase(blogid)) {
					if(element.getChild("references").getChildren().size()!=0) {
						Iterator cIterator = element.getChild("references").getChildren().iterator();
						do {
							Element cElement = (Element)cIterator.next();
							BlogReference reference = new BlogReference(cElement);
							references.add(reference);
						}while(cIterator.hasNext());
					}
				}
			}while(iterator.hasNext());
		}
		return (BlogReference[])references.toArray(new BlogReference[0]);
	}
	/**
	 * 将日志输出为持久化的XML文档
	 * @param bloges
	 * @throws Exception
	 */
	public void outputXMLDocument(Blog[] bloges) throws Exception {
		File file = new File(BlogService.class.getResource("blog.xml").getPath());
		if(file.exists()) file.delete();
		if(!file.exists()) file.createNewFile();
		FileOutputStream stream = new FileOutputStream(file);
		Document doc = new Document();
		Element root = new Element("bloges");
		if((bloges!=null)&&(bloges.length!=0)) {
			for(int i=0;i<bloges.length;i++) {
				Element element = new Element("blog");
				element.setAttribute("id",bloges[i].getId());
				Element title = new Element("title").addContent(bloges[i].getTitle());
				Element catalogue = new Element("catalogue").addContent(bloges[i].getCatalogue());
				Element publishdate = new Element("publishdate").addContent(bloges[i].getPublishdate());
				CDATA conCDATA = new CDATA(bloges[i].getContent());
				Element content = new Element("content").addContent(conCDATA);
				Element entry = new Element("entry").addContent(bloges[i].getEntry());
				Element track = new Element("track").addContent(bloges[i].getTrack());
				Element images = new Element("images");
				if((bloges[i].getImages()!=null)&&(bloges[i].getImages().size()!=0)) {
					BlogImage[] iArray = (BlogImage[])bloges[i].getImages().toArray(new BlogImage[0]);
					for(int j=0;j<iArray.length;j++) {
						Element image = new Element("image");
						image.addContent(new Element("imageName").addContent(iArray[j].getImageName()));
						image.addContent(new Element("url").addContent(iArray[j].getUrl()));
						images.addContent(image);
					}
				}
				Element comments = new Element("comments");
				BlogComment[] cArray = (BlogComment[])bloges[i].getComments().toArray(new BlogComment[0]);
				if((cArray!=null)&&(cArray.length!=0)) {
					for(int j=0;j<cArray.length;j++) {
						Element comment = new Element("comment");
						comment.addContent(new Element("author").addContent(cArray[j].getAuthor()));
						comment.addContent(new Element("blogimage").addContent(cArray[j].getBlogimage()));
						comment.addContent(new Element("commentdate").addContent(cArray[j].getCommentdate()));
						comment.addContent(new Element("blogurl").addContent(cArray[j].getBlogurl()));
						comment.addContent(new Element("email").addContent(cArray[j].getEmail()));
						CDATA cdata = new CDATA(cArray[j].getCommentcontent());
						comment.addContent(new Element("commentcontent").addContent(cdata));
						comments.addContent(comment);
					}
				}
				Element commenttotal = new Element("commenttotal").addContent(String.valueOf(cArray.length));
				Element references = new Element("references");
				BlogReference[] rArray = 
					(BlogReference[])bloges[i].getReferences().toArray(new BlogReference[0]);
				if((rArray!=null)&&(rArray.length!=0)) {
					for(int j=0;j<rArray.length;j++) {
						Element reference = new Element("reference");
						reference.addContent(new Element("refername").addContent(rArray[i].getRefername()));
						reference.addContent(new Element("referurl").addContent(rArray[i].getReferurl()));
						references.addContent(reference);
					}
				}
				Element referencetotal = 
					new Element("referencetotal").addContent(String.valueOf(rArray.length));
				element.addContent(title);
				element.addContent(catalogue);
				element.addContent(publishdate);
				element.addContent(content);
				element.addContent(entry);
				element.addContent(track);
				element.addContent(images);
				element.addContent(comments);
				element.addContent(commenttotal);
				element.addContent(references);
				element.addContent(referencetotal);
				root.addContent(element);
			}
		}
		doc.addContent(root);
		XMLOutputter outputter = 
			new XMLOutputter(Format.getPrettyFormat().setEncoding("gb2312"));
		outputter.output(doc,stream);
	}
	/**
	 * 输出指定日志的全部评论为XML文档
	 * @param out
	 * @param blogid
	 * @throws Exception
	 */
	public void outputComment(PrintWriter out, String blogid) throws Exception {
		BlogComment[] commentes = this.getComment(blogid);
		Document doc = new Document();
		Element root = new Element("commentes");
		if((commentes!=null)&&(commentes.length!=0)) {
			for(int i=0;i<commentes.length;i++) {
				Element element = new Element("comment");
				Element author = new Element("author").addContent(commentes[i].getAuthor());
				Element blogimage = new Element("blogimage").addContent(commentes[i].getBlogimage());
				Element commentdate = new Element("commentdate").addContent(commentes[i].getCommentdate());
				Element blogurl = new Element("blogurl").addContent(commentes[i].getBlogurl());
				Element email = new Element("email").addContent(commentes[i].getEmail());
				Element commentcontent = new Element("commentcontent").addContent(commentes[i].getCommentcontent());
				element.addContent(author);
				element.addContent(blogimage);
				element.addContent(commentdate);
				element.addContent(blogurl);
				element.addContent(email);
				element.addContent(commentcontent);
				root.addContent(element);
			}
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO8859-1"));
		outputter.output(doc,out);
	}
	/**
	 * 输出指定日志的全部引用为XML文档
	 * @param out
	 * @param blogid
	 * @throws Exception
	 */
	public void outputReference(PrintWriter out, String blogid) throws Exception {
		BlogReference[] references = this.getReference(blogid);
		Blog blog = this.getBlog(blogid);
		Document doc = new Document();
		Element root = new Element("references");
		Element track = new Element("track").addContent(blog.getTrack());
		root.addContent(track);
		if((references!=null)&&(references.length!=0)) {
			for(int i=0;i<references.length;i++) {
				Element element = new Element("reference");
				Element refername = new Element("refername").addContent(references[i].getRefername());
				Element referurl = new Element("referurl").addContent(references[i].getReferurl());
				element.addContent(refername);
				element.addContent(referurl);
				root.addContent(element);
			}
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO8859-1"));
		outputter.output(doc,out);
	}
	/**
	 * 获取全部的自定义列表，以对象数组的形式返回
	 * @return
	 * @throws Exception
	 */
	public BlogList[] getAllList() throws Exception{
		Collection bloglist = new ArrayList();
		if(this.listdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.listdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				BlogList list = new BlogList();
				list.initialItem(element);
				bloglist.add(list);
			}while(iterator.hasNext());
			return (BlogList[])bloglist.toArray(new BlogList[0]);
		}
		else 
			return new BlogList[0];
	}
	/**
	 * 获取全部的自定义列表，以Map的形式返回
	 * @return
	 * @throws Exception
	 */
	public Map getAllListMap() throws Exception {
		Map bloglist = new HashMap();
		if(this.listdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.listdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				BlogList list = new BlogList();
				list.initialItem(element);
				bloglist.put(list.getListid(),list);
			}while(iterator.hasNext());
			return bloglist;
		}
		else 
			return bloglist;
	}
	/**
	 * 获取指定编号的自定义列表
	 * @param listid
	 * @return
	 * @throws Exception
	 */
	public BlogList getBlogList(String listid) throws Exception {
		BlogList list = null;
		if(this.listdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.listdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("listid").equalsIgnoreCase(listid)){
					list = new BlogList();
					list.initialItem(element);
				}
			}while(iterator.hasNext());
		}
		return list;
	}
	/**
	 * 获取指定自定义列表的全部列表项目，以对象数组的形式返回
	 * @param listid
	 * @return
	 * @throws Exception
	 */
	public BlogListItem[] getAllListItem(String listid) throws Exception {
		Collection itemes = new ArrayList();
		if(this.listdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.listdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("listid").equalsIgnoreCase(listid)) {
					if(element.getChildren("item").size()!=0) {
						Iterator cIterator = element.getChildren("item").iterator();
						do {
							Element cElement = (Element)cIterator.next();
							BlogListItem item = new BlogListItem(cElement);
							itemes.add(item);
						}while(cIterator.hasNext());
					}
				}
			}while(iterator.hasNext());
		}
		return (BlogListItem[])itemes.toArray(new BlogListItem[0]);
	}
	/**
	 * 获取指定自定义列表的列表项目，以Map的形式返回
	 * @param listid
	 * @return
	 * @throws Exception
	 */
	public Map getAllListItemMap(String listid) throws Exception {
		Map itemes = new HashMap();
		if(this.listdom.getRootElement().getChildren().size()!=0) {
			Iterator iterator = this.listdom.getRootElement().getChildren().iterator();
			do {
				Element element = (Element)iterator.next();
				if(element.getAttributeValue("listid").equalsIgnoreCase(listid)) {
					if(element.getChild("item").getChildren().size()!=0) {
						Iterator cIterator = element.getChild("item").getChildren().iterator();
						do {
							Element cElement = (Element)cIterator.next();
							BlogListItem item = new BlogListItem(cElement);
							itemes.put(item.getItemid(),item);
						}while(cIterator.hasNext());
					}
				}
			}while(iterator.hasNext());
		}
		return itemes;
	}
	/**
	 * 获取指定的列表项
	 * @param listid
	 * @param itemid
	 * @return
	 * @throws Exception
	 */
	public BlogListItem getListItem(String listid, String itemid) throws Exception {
		BlogListItem[] itemes = this.getAllListItem(listid);
		BlogListItem item = null;
		if((itemes!=null)&&(itemes.length!=0)) {
			for(int i=0;i<itemes.length;i++) {
				if(itemid.equalsIgnoreCase(itemes[i].getItemid())) {
					item = itemes[i];
					break;
				}
			}
		}
		return item;
	}
	/**
	 * 往指定自定义列表中添加列表项目
	 * @param listid
	 * @param item
	 * @throws Exception
	 */
	public void addListItem(String listid, BlogListItem item) throws Exception {
		BlogList[] listes = this.getAllList();
		if((listes!=null)&&(listes.length!=0)) {
			for(int i=0;i<listes.length;i++) {
				if(listid.equalsIgnoreCase(listes[i].getListid())) {
					item.setItemid(String.valueOf(this.getAllListItem(listes[i].getListid()).length+1));
					listes[i].getListitem().put(item.getItemid(),item);
					break;
				}
			}
			this.outputListDocument(listes);
		}
	}
	/**
	 * 删除指定的列表项目
	 * @param listid
	 * @param itemid
	 * @throws Exception
	 */
	public void deleteListItem(String listid, String itemid) throws Exception {
		BlogList[] listes = this.getAllList();
		if((listes!=null)&&(listes.length!=0)) {
			for(int i=0;i<listes.length;i++) {
				if(listid.equalsIgnoreCase(listes[i].getListid())) {
					listes[i].getListitem().remove(itemid);
				}
			}
		}
		this.outputListDocument(listes);
	}
	/**
	 * 更新指定的列表项目
	 * @param listid
	 * @param item
	 * @throws Exception
	 */
	public void updateListItem(String listid, BlogListItem item) throws Exception {
		BlogList[] listes = this.getAllList();
		if((listes!=null)&&(listes.length!=0)) {
			for(int i=0;i<listes.length;i++) {
				if(listid.equalsIgnoreCase(listes[i].getListid())) {
					listes[i].getListitem().put(item.getItemid(),item);
				}
			}
		}
		this.outputListDocument(listes);
	}
	/**
	 * 输出自定义列表到XML持久文档
	 * @param listes
	 * @throws Exception
	 */
	public void outputListDocument(BlogList[] listes) throws Exception {
		File file = new File(BlogService.class.getResource("list.xml").getPath());
		if(file.exists()) file.delete();
		if(!file.exists()) file.createNewFile();
		FileOutputStream stream = new FileOutputStream(file);
		Document doc = new Document();
		Element root = new Element("listes");
		for(int i=0;i<listes.length;i++) {
			Element list = new Element("list");
			list.setAttribute("listid",listes[i].getListid());
			list.setAttribute("listname",listes[i].getListname());
			Element itemtotal = new Element("itemtotal").addContent(String.valueOf(listes[i].getItemtotal()));
			list.addContent(itemtotal);
			if((listes[i].getListitem()!=null)&&(listes[i].getListitem().size()!=0)) {
				Iterator iterator = listes[i].getListitem().values().iterator();
				do {
					BlogListItem item = (BlogListItem)iterator.next();
					Element itemElement = new Element("item");
					itemElement.setAttribute("itemid",item.getItemid());
					Element itemname = new Element("itemname").addContent(item.getItemname());
					Element itemurl = new Element("itemurl").addContent(item.getItemurl());
					CDATA cdata = new CDATA(item.getDescription());
					Element description = new Element("description").addContent(cdata);
					itemElement.addContent(itemname);
					itemElement.addContent(itemurl);
					itemElement.addContent(description);
					list.addContent(itemElement);
				}while(iterator.hasNext());
			}
			root.addContent(list);
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("gb2312"));
		outputter.output(doc,stream);
	}
	/**
	 * 输出指定自定义列表为XML文档
	 * @param out
	 * @param listes
	 * @throws Exception
	 */
	public void outputList(PrintWriter out, BlogList[] listes) throws Exception {
		Document doc = new Document();
		Element root = new Element("listes");
		for(int i=0;i<listes.length;i++) {
			Element list = new Element("list");
			list.setAttribute("listid",listes[i].getListid());
			list.setAttribute("listname",listes[i].getListname());
			if((listes[i].getListitem()!=null)&&(listes[i].getListitem().size()!=0)) {
				Iterator iterator = listes[i].getListitem().values().iterator();
				do {
					BlogListItem item = (BlogListItem)iterator.next();
					Element itemElement = new Element("item");
					itemElement.setAttribute("itemid",item.getItemid());
					Element itemname = new Element("itemname").addContent(item.getItemname());
					Element itemurl = new Element("itemurl").addContent(item.getItemurl());
					Element description = new Element("description").addContent(item.getDescription());
					itemElement.addContent(itemname);
					itemElement.addContent(itemurl);
					itemElement.addContent(description);
					list.addContent(itemElement);
				}while(iterator.hasNext());
			}
			root.addContent(list);
		}
		doc.addContent(root);
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO8859-1"));
		outputter.output(doc,out);
	}
	/**
	 * 处理系统异常
	 * @param ex
	 */
	private void handleError(Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.toString());
	}
}
